<template>
	<view class="home_container">
		<view class="bg_img"></view>
		<view class="content_container">
			<view class="swiper_container">
				<u-swiper :list="swiperList" keyName="image" @click="swiperClick"></u-swiper>
			</view>
			<view class="btn_container">
				<view class="textBtn" @click="textClick()">
					<image src="../../static/img/main/pointer.png" mode="widthFix"></image>
					<view class="text">
						<view style="font-size: 32rpx;">立即检测</view>
						<view style="font-size: 16rpx;">Check Now</view>
					</view>
				</view>
				<view class="tab_container">
					<view v-for="(item,index) in btn" :key="index" @click="btnClick(index)" class="tab_item">
						<view class="img">
							<image :src="item.img" mode="aspectFit"></image>
						</view>
						<view class="name">{{item.name}}</view>
					</view>
				</view>
			</view>
			<view class="activity_container">
				<view class="activ_item" @click="activeHandle(1)">
					<view class="">优惠活动</view>
					<view class="img">
						<image src="http://applet.atptest.com/kYgxEBHj1725499204813.png?v=1725499205308"></image>
					</view>
				</view>
				<view class="activ_item" @click="activeHandle(3)" v-if="userInfo.agentId && userInfo.headUserId">
					<view>分销管理</view>
					<view class="img">
						<image src="http://applet.atptest.com/c7OaCzeD1725499246205.png?v=1725499246428"></image>
					</view>
				</view>
				<view class="activ_item" @click="activeHandle(2)" v-if="!userInfo.agentId && !userInfo.headUserId && !userInfo.isFans">
					<view>分销商申请</view>
					<view class="img">
						<image src="http://applet.atptest.com/c7OaCzeD1725499246205.png?v=1725499246428"></image>
					</view>
				</view>
				<view class="activ_item" @click="activeHandle(4)" v-if="!userInfo.agentId && !userInfo.headUserId && userInfo.isFans">
					<view>个人中心</view>
					<view class="img">
						<image src="http://applet.atptest.com/aNQG6aCC1725608200758.png?v=1725608200970"></image>
					</view>
				</view>
			</view>
		</view>

		<u-modal :show="show" @confirm="toCoupon" @cancel="show=false" confirmText="去查看" cancelText="取消"
			:showCancelButton="true" :asyncClose="true" title="优惠券消息" :content='currentTitle'></u-modal>

		<AccreditModal v-if="accreditFlag" @closeAccrredit='closeAccrredit' />
	</view>
</template>

<script>
	import {
		getCodeByLink,
		giveCouponById,
		getNewCouponsCount,
		PageList_Article,
		GetUserInfo,
	} from '../../api/user.js'
	import AccreditModal from "../accredit/accreditModal.vue"
	import {
		mapState,
		mapMutations
	} from 'vuex'
	export default {
		components: {
			AccreditModal
		},
		data() {
			return {
				currentTitle: '',
				code: '',
				show: false,
				accreditFlag: false,
				shareCode: '', // 分享的code
				imgUrl: '',
				swiperList: [{
					image: 'http://applet.atptest.com/SmhqQGgq1725500058454.png',
				}],
				btn: [{
						name: "关于我们",
						img: require('../../static/img/main/icon/icon1.png')
					},
					{
						name: "会员中心",
						img: require('../../static/img/main/icon/icon2.png')
					},
					{
						name: "检测订单",
						img: require('../../static/img/main/icon/icon3.png')
					},
					{
						name: "联系我们",
						img: require('../../static/img/main/icon/icon4.png')
					}
				],
				newsList: [],
				size: 5,
				pageIndex: 1,
				bottomShow: false,
				agentId: "",
				openId: "",
			};
		},
		computed: {
			...mapState('user', ['userInfo', 'token']) // vuex
		},
		// 上拉加载
		// onReachBottom() {
		// 	this.pageIndex++
		// 	// this.getNewslist({
		// 	// 	size: this.size,
		// 	// 	pageIndex: this.pageIndex,
		// 	// })
		// },

		onShow() {
			this._getNewCouponsCount() // 不管是不是新用户和老用户 赠送的逻辑
			this.getUserInfo()
			// this.getNewslist({
			// 	size: this.size,
			// 	pageIndex: this.pageIndex,
			// })
			let timestamp = Date.now()
			this.swiperList[0].image = "http://applet.atptest.com/SmhqQGgq1725500058454.png?v=" + timestamp
		},

		onLoad(options) {
			console.log("options", options);
			// 用户点击小程序分享的优惠券 在这里获取code 用户后续转送操作 
			if (options.code) {
				this.shareCode = options.code
				this.getLinks(options.code)
			}
			//新用户通过分享的二维码/短链接进来，自动分配到指定的业务员或分销商下
			if (options.agentId) { //短链接
				this.agentId = options.agentId
			}
			if (options.scene) { //二维码
				const scene = decodeURIComponent(options.scene);
				console.log("scene", scene);
				this.agentId = scene;
			}
			// token不存在，调小程序登陆接口获取code,通过code获取token
			if (!uni.getStorageSync('token')) {
				this.getInfo()
			}

		},

		onHide() {
			this.pageIndex = 1
			this.newsList = []
		},
		methods: {
			...mapMutations('user', ['setUserInfo', 'setToken']),

			// 立即检测按钮
			textClick() {
				uni.switchTab({
					url: '/pages/test/test'
				})
			},

			//轮播图
			swiperClick(e) {
				if (e == 0 && !this.userInfo.companyPhone) {
					uni.navigateTo({
						url: '/pagesB/pages/mineInfo/mineInfo'
					})
				}
			},

			// 获取用户信息
			getUserInfo() {
				GetUserInfo().then((res) => {
					this.setUserInfo(res)
					if (!res.companyPhone) {
						this.accreditFlag = true;
					} else {
						this.accreditFlag = false;
					}
				})
			},
			//关闭授权弹框
			closeAccrredit(val) {
				this.accreditFlag = val
			},
			btnClick(i) {
				if (i == 0) {
					uni.navigateTo({
						url: '/pagesA/pages/intro/intro'
					})
				} else if (i == 3) {
					uni.navigateTo({
						url: '/pagesA/pages/contact/contact'
					})
				} else if (i == 2) {
					uni.navigateTo({
						url: '/pagesB/pages/order/order?i=99'
					})
				} else if (i == 1) {
					uni.navigateTo({
						url: '/pagesB/pages/memberCenter/memberCenter'
					})
				}
			},

			//活动
			activeHandle(i) {
				if (i == 1) {
					if (!this.userInfo.companyPhone) {
						uni.navigateTo({
							url: '/pagesB/pages/mineInfo/mineInfo'
						})
					} else {
						uni.navigateTo({
							url: '/pagesA/pages/coupon/coupon'
						})
					}
				} else if (i == 2) {
					if (!this.userInfo.companyPhone) {
						uni.navigateTo({
							url: '/pagesB/pages/mineInfo/mineInfo'
						})
					} else {
						uni.navigateTo({
							url: '/pagesB/pages/distributorApply/distributorApply'
						})
					}
				}else if(i == 3){
					uni.navigateTo({
						url: '/pagesA/pages/distribution/distribution?agentId=' + this.userInfo.agentId
					})
				}else if(i == 4){
					uni.switchTab({
						url: '/pages/mine/mine'
					})
				}
			},

			// 获取token
			getInfo() {
				uni.login({
					provider: 'weixin',
					success: (res) => {
						console.log("登录code", res);
						this.code = res.code
						this.getToken()
					}
				})
			},

			// 获取token
			async getToken() {
				const _that = this
				uni.request({
					url: 'https://wechat.atptest.com:44386/connect/token',
					data: {
						code: _that.code,
						grant_type: 'wechat',
						AgentId: _that.agentId
					},
					method: 'POST',
					header: {
						'content-type': 'application/x-www-form-urlencoded',
						'Authorization': 'Basic QXBpX1dlYjpBcGlfV2Vi'
					},
					success(res) {
						_that.setToken(res.data.access_token)
					}
				})
			},

			// 根据获取到的分享用户点击进来携带的code 来获取链接地址
			async getLinks(x) {
				let result = await getCodeByLink({
					code: x
				})
				if (result.url) {
					let y = result.url.split('=')
					const couponPersonId = y[1]
					let data = {
						couponPersonId,
						code: this.shareCode
					}
					// 唤起赠送优惠券的接口
					let res = await giveCouponById(data)
					if (res == true) {
						this._getNewCouponsCount() //判断是否有新的优惠券 执行弹窗
					} else {
						return uni.showToast({
							title: res.message,
							icon: 'error'
						})
					}
				} else {
					// console.error(result);
				}
			},

			// 跳转到优惠券广场
			toCoupon() {
				this.show = false
				uni.navigateTo({
					url: '/pagesB/pages/memberCenter/memberCenter?state=0'
				})
			},

			// 判断是否有新的优惠券 执行弹窗
			async _getNewCouponsCount() {
				let data = await getNewCouponsCount()
				if (data) {
					this.show = true
					this.currentTitle = `恭喜您获得${data}张新的优惠券，期待您的使用。`
				}
			},
			// 获取新闻列表
			getNewslist(e) {
				PageList_Article(e).then((res) => {
					if (res == null) {
						this.bottomShow = true
						return
					}
					this.newsList = this.newsList.concat(res.items)
				})
			},
			// 跳转新闻详情
			toNewsDetail(id) {
				uni.navigateTo({
					url: `/pagesA/pages/newsDetails/newsDetails?id=${id}`
				})
			}
		},


	}
</script>

<style lang="scss" scoped>
	.home_container {
		width: 100%;
		min-height: 100vh;
		background-color: #f1f1f1;

		.bg_img {
			width: 100%;
			height: 460rpx;
			background: url("http://applet.atptest.com/ga3KTvEj1725442008261.png?v=1725442008940") no-repeat;
			background-size: cover;
		}

		.content_container {
			width: 100%;
			padding: 30rpx 20rpx;
			box-sizing: border-box;

			.swiper_container {
				width: 100%;
				height: 220rpx;

				/deep/ .u-swiper {
					height: 220rpx !important;
				}

				/deep/ .u-swiper__wrapper {
					height: 220rpx !important;
				}

				/deep/ .u-swiper__wrapper__item {
					height: 220rpx !important;
				}

				/deep/ .u-swiper__wrapper__item__wrapper {
					image {
						height: 220rpx !important;
					}
				}
			}

			.btn_container {
				width: 100%;
				height: 340rpx;
				border-radius: 16rpx;
				background-color: #fff;
				padding: 40rpx 56rpx;
				box-sizing: border-box;
				margin-top: 20rpx;

				.textBtn {
					width: 100%;
					height: 100rpx;
					border-radius: 16rpx;
					display: flex;
					justify-content: center;
					align-items: center;
					background: linear-gradient(270.00deg, rgb(1, 25, 110) 0%, rgb(63, 89, 191) 100%);

					image {
						width: 60rpx;
					}

					.text {
						display: flex;
						flex-direction: column;
						justify-content: center;
						align-items: center;
						color: #eee;
						margin-left: 10rpx;
					}
				}

				.tab_container {
					width: 100%;
					display: flex;
					justify-content: space-between;
					align-items: center;
					margin-top: 40rpx;

					.tab_item {
						display: flex;
						flex-direction: column;
						align-items: center;
						font-size: 24rpx;

						.img {
							width: 60rpx;
							height: 60rpx;

							image {
								width: 100%;
								height: 100%;
							}
						}

						.name {
							margin-top: 16rpx;
						}
					}
				}
			}

			.activity_container {
				width: 100%;
				padding: 40rpx;
				padding-bottom: 0;
				box-sizing: border-box;
				border-radius: 16rpx;
				background-color: #fff;
				margin-top: 20rpx;
				display: flex;
				flex-wrap: wrap;
				justify-content: space-between;
				align-items: center;

				.activ_item {
					width: 45%;
					height: 100rpx;
					border-radius: 8rpx;
					background-color: #94A2E2;
					font-size: 24rpx;
					display: flex;
					align-items: center;
					padding-left: 24rpx;
					box-sizing: border-box;
					position: relative;
					margin-bottom: 40rpx;

					.img {
						width: 130rpx;
						height: 130rpx;
						position: absolute;
						bottom: 0;
						right: 0;

						image {
							width: 100%;
							height: 100%;
						}
					}

				}
			}
		}


	}
</style>